import Vue from "vue";
import axios from "axios";

const service = axios.create({
  // public中 地址
  baseURL: window.VUE_APP_BASE_URL,
  // .env... 中地址
  // baseURL: process.env.VUE_APP_BASE_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000, // request timeout
});
service.defaults.withCredentials = true;
// 请求拦截
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 拦截response 事先统一处理
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      Vue.prototype.$message.error(res.msg); //文字提示
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    Vue.prototype.$message.error("网络错误"); //文字提示
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);
// 把axios放到全局中
Vue.prototype.$http = service;
export default service;
